package com.seari.task;

import com.seari.bean.CreateTableInfo;
import com.seari.bean.DropTableInfo;
import com.seari.bean.MetroFluxnew;
import com.seari.service.ReadFileDataInsertToOraService;
import com.seari.util.FormatDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Service("readFileDataInsertToOra")
@PropertySource("classpath:cron.props")
public class ReadFileDataInsertToOra {

    private static final Logger log = LoggerFactory.getLogger(ReadFileDataInsertToOra.class);

    @Value("${tableName}")
    public String tableName;

    @Autowired
    private ReadFileDataInsertToOraService readFileDataInsertToOraService;

    //文件夹路径
    @Value("${basePath}")
    public String basePath;

    @Value("${basePathBak}")
    public String basePathBak;

    //每五分钟同步仪电客流数据到本地数据库中
    @Scheduled(cron="${jobs.sysdata.schedule}")
    public void symFlieDataToOra() {
        log.info("=======  symFlieDataToOra  start=======");

        try {
            //插入的表名字
            CreateTableInfo ctToday = new CreateTableInfo();
            Calendar cal=Calendar.getInstance();
            String todayStr = FormatDateTime.toAFCTableNameDateString(cal.getTime());
            StringBuffer sb = new StringBuffer(tableName);
            sb.append(todayStr);
            String s = sb.toString();

            String fileName = "FLUXNEW_SEG_";
            String[] list=new File(basePath).list();
            for(String fileStr:list){
                if(fileStr.contains(fileName))
                {
                    //文件路径   处理客流文件数据入库
                    String fileBasePath = basePath+fileStr;
                    String fileBasePathBak = basePathBak+fileStr;

                    List<MetroFluxnew> metroFluxnews = toArrayByFileReader1(fileBasePath);
                    readFileDataInsertToOraService.insertPDDataToDatabases(s,metroFluxnews);
                    moveFiles(fileBasePath,fileBasePathBak);

                } else {
                    //暂不处理其他文件内容 将其全部移动到备份目录
                    String fileBasePath = basePath+fileStr;
                    String fileBasePathBak = basePathBak+fileStr;
                    moveFiles(fileBasePath,fileBasePathBak);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
        log.info("=======  symFlieDataToOra  end  =======");
    }

    //每天一点建表  TBL_METRO_FLUXNEW_yyyymmdd  一天建立两张表  今天和明天的
    //@Scheduled(cron="${jobs.createtable.schedule}")
    public void createTable() {
        createTableImpl();
    }

    //删除一个月之前的表  每天早上一点执行  drop 表oralce mybaties 只能一张一张的删除
    //@Scheduled(cron="${jobs.deleteTable.schedule}")
    public void deleteTable() {

        List<DropTableInfo>  dropList = new ArrayList<DropTableInfo>();

        try {
            List<DropTableInfo> dropTableList = readFileDataInsertToOraService.selectTableInfo();
            if (dropTableList!=null||dropTableList.size()!=0){
                for(DropTableInfo dropTableInfo : dropTableList){
                    String[] str = dropTableInfo.getTname().split("_");
                    String datestr = str[str.length-1];
                    Boolean boo = judgeDate(datestr);

                    if (boo){
                        String todayDateStr = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
                        if (Integer.parseInt(datestr)<Integer.parseInt(todayDateStr)-30){
                            dropList.add(dropTableInfo);
                        }
                    }
                }
            }

            readFileDataInsertToOraService.dropTable(dropList);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //删除一个月之前文件  每月1号执行  bak目录
    //@Scheduled(cron="${jobs.deleteFile.schedule}")
    public void deleteFile() {

        log.info("=======  deleteFile  start =======");
        File dir=new File(basePathBak);
        removeDirFile(dir);
        log.info("=======  deleteFile  end  =======");
    }

    public List<MetroFluxnew> toArrayByFileReader1(String name) {
        // 使用ArrayList来存储每行读取到的对象
        ArrayList<MetroFluxnew> arrayList = new ArrayList<MetroFluxnew>();
        // 使用ArrayList来存储每行读取到的字符串
        ArrayList<String> strList = new ArrayList<String>();
        try {
            FileReader fr = new FileReader(name);
            BufferedReader bf = new BufferedReader(fr);
            String str;
            // 按行读取字符串
            while ((str = bf.readLine()) != null) {
                strList.add(str);
            }
            bf.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(strList==null||strList.size()==0){
            return null;
        }

        // 对ArrayList中存储的字符串进行处理
        for (int i = 0; i < strList.size(); i++) {
            boolean boo = true;
            String[] strpd = strList.get(i).split(",");
            for(String st : strpd){
                if(st == null||st==""||strpd.length!=6){
                    boo = false;
                }
            }
            if (boo = true){
                MetroFluxnew mfn = new MetroFluxnew();
                for(int j = 0;j <  strpd.length;j++){
                    mfn.setStationId(strpd[1]);
                    mfn.setStartTime(strpd[2]);
                    mfn.setEndTime(strpd[3]);
                    mfn.setEnterTimes(Float.parseFloat(strpd[4]));
                    mfn.setExitTimes(Float.parseFloat(strpd[5]));
                }
                arrayList.add(mfn);
            }

        }
        // 返回数组
        return arrayList;
    }

    public void createTableImpl(){
          CreateTableInfo ctToday = new CreateTableInfo();
          CreateTableInfo ctTomorrow = new CreateTableInfo();
          Calendar cal=Calendar.getInstance();

          String todayStr = FormatDateTime.toAFCTableNameDateString(cal.getTime());
          ctToday.setTableName(tableName+todayStr);

          cal.add(cal.DATE, 1);
          String tomorrowStr = FormatDateTime.toAFCTableNameDateString(cal.getTime());
          ctTomorrow.setTableName(tableName+tomorrowStr);

          log.info("=======  createTable  start=======");
          try {
              int todayNum = readFileDataInsertToOraService.judgeTableIsorNotExist(ctToday);
              int tomorrowNum = readFileDataInsertToOraService.judgeTableIsorNotExist(ctTomorrow);
              log.info("=======  todayNum=======  todayNum" +todayNum+"   "+tomorrowNum);

              if(todayNum==0)
              {
                  readFileDataInsertToOraService.createTable(ctToday);
                  log.info("=======  createTable  start  today table success=======");
              }
              else if (todayNum==1)
              {
                  log.info("=======  createTable  start  today table is exist=======");
              }

              if(tomorrowNum==0)
              {
                  readFileDataInsertToOraService.createTable(ctTomorrow);
                  log.info("=======  createTable  start  tomorrow table success=======");
              }
              else if (tomorrowNum==1)
              {
                  log.info("=======  createTable  start  tomorrow table is exist=======");
              }

          }catch (Exception e){
              e.printStackTrace();
          }

          log.info("=======  createTable  end  =======");
      }

    public void moveFiles(String fileBasePath,String fileBasePathBak){

        File file=new File(fileBasePath); //源文件
        if (file.renameTo(new File(fileBasePathBak)))//源文件移动至目标文件目录
        {
            log.info("=======  moveFiles  success  =======");//输出移动成功
        }
        else
        {
            log.info("=======  moveFiles  failed  =======");//输出移动失败
        }
    }

    public void removeDirFile(File dir){
        File[] files=dir.listFiles();
        for(File file:files){
            if(file.isDirectory()){
                removeDirFile(file);
            }else{
                log.info("=======  removeDir son file success  =======");
            }
        }
        log.info("=======  removeDir file success  =======");
    }

    public boolean judgeDate(String str){

        //正则表达式 用来校验日期  yyyymmdd字符串
        String reg_yyyyMMdd = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))" +
                "|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))" +
                "|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229)";
        Pattern p = Pattern.compile(reg_yyyyMMdd);
        Matcher m = p.matcher(str);
        return m.matches();
    }
}
